package com.tangding.eventBus;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.springframework.stereotype.Component;

import com.google.common.base.Strings;
import com.tangding.common.eventbus.EventBus;
import com.tangding.common.logx.LogHelp;
import com.tangding.common.utils.Utils;

/**
 * @description 
 *
 * @author Ranger
 * @version 2017年5月4日_下午8:38:51
 *
 */
//@Component
public class EventBusFixed extends EventBusPool{
	Map<Integer, Pair<EventBus, EventBus>> cache = new HashMap<Integer, Pair<EventBus, EventBus>>();
	
	private int busCount = Runtime.getRuntime().availableProcessors() * 2;
	
	@PostConstruct
	public void init() {
		for (int i = 0; i < busCount; i++) {
			Pair<EventBus, EventBus> pair = buildPairBus(i);
			cache.put(i, pair);
		}
	}
	
	@Override
	public EventBus get(String uid, UserEventType type) {
		try {
			if (Strings.isNullOrEmpty(uid)) {
				return null;
			}
			int index = Utils.hashRule(cache.size(), uid);
			if (type == UserEventType.REQUEST) {
				return cache.get(index).first;
			}else if (type == UserEventType.RESPONSE) {
				return cache.get(index).second;
			}
		} catch (Exception e) {
			LogHelp.doLogException(e);
		}
		return null;
	}
	
	@Override
	public void remove(String uid) {
		cache.remove(uid);
	}

	public int getBusCount() {
		return busCount;
	}

	public void setBusCount(int busCount) {
		this.busCount = busCount;
	}
}